package aau.client;

import aau.client.geo.Point;
import aau.client.geo.StickyLine;
import aau.client.geo.Vector;
import aau.client.ui.Circle;
import aau.client.ui.Layer;

import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.user.client.ui.RootPanel;

public class App implements EntryPoint, RepeatingCommand {
    private Canvas canvas;
    private Layer contents;

    @Override
    public void onModuleLoad() {
        this.canvas = Canvas.createIfSupported();
        this.canvas.setWidth("640px");
        this.canvas.setHeight("480px");
        this.canvas.setCoordinateSpaceWidth(320);
        this.canvas.setCoordinateSpaceHeight(240);
        RootPanel.get().add(this.canvas);

        this.contents = new Layer();
        Circle cl = new Circle();
        cl.setRadius(Math.random() * 20 + 15);
        cl.setLocation(new Point(160, 120));
        this.contents.add(cl);

        Point offset = cl.getLocation();

        Vector v = new Vector(Math.random(), Math.random() * 100);
        double r = Math.random() * 100 + cl.getRadius();

        int partcle = (int) (Math.random() * 30);

        for (int i = 0; i < partcle; i++) {
            double theta = Math.random() * 2d * Math.PI;

            Circle particle = new Circle();
            particle.setLocation(offset.add(v).add(new Vector(theta, r + Math.random() * r - r / 2)));
            particle.setRadius(Math.random() * 6);
            this.contents.add(particle);

            StickyLine sl = new StickyLine();
            sl.setFrom(cl);
            sl.setDestination(particle);
            this.contents.add(sl);
        }

        render();
        Scheduler.get().scheduleIncremental(this);
    }

    private void render() {
        Context2d c = this.canvas.getContext2d();
        this.contents.paint(c);
    }

    @Override
    public boolean execute() {
        render();
        return true;
    }
}
